package com.fangzhi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ExcelToImage {
    public static void main(String[] args) {
        try {
            // 读取 Excel 文件
            FileInputStream fis = new FileInputStream("/Users/edy/self/fangzhi/excel/new.xlsx");
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);

            // 获取前三行前三列的数据
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < 3; i++) {
                Row row = sheet.getRow(i);
                if (row!= null) {
                    for (int j = 0; j < 3; j++) {
                        Cell cell = row.getCell(j);
                        if (cell!= null) {
                            content.append(getCellValue(cell)).append("\t");
                        } else {
                            content.append("\t");
                        }
                    }
                    content.append("\n");
                }
            }

            fis.close();
            workbook.close();

            // 将获取到的数据转换为图片
            convertToImage(content.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getCellValue(Cell cell) {
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }

    private static void convertToImage(String content) {
        int width = 800;
        int height = 600;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.BLACK);
        Font font = new Font("Arial", Font.PLAIN, 20);
        g2d.setFont(font);

        int x = 50;
        int y = 50;
        for (String line : content.split("\n")) {
            g2d.drawString(line, x, y);
            y += 30;
        }

        g2d.dispose();

        try {
            String property = System.getProperty("user.dir");
            // 保存图片为 PNG 格式
            ImageIO.write(image, "png", new File(property + "/avatar/excel_content_image.png"));
            System.out.println("图片生成成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}